package eor

import (
	"fmt"
	"runtime/debug"
	"svr/src/logs"
	"svr/src/msg"
)

func NewErrSafed(code msg.ErrCode, pos string, num interface{}, v ...interface{}) *msg.Error {
	var err *msg.Error
	if v == nil || len(v) == 0 {
		err = &msg.Error{Code: code}
	} else {
		str0, str1 := combString(v...)
		err = &msg.Error{Code: code, Result: str0, ErrString: str1}

	}
	printErrSafed(err, pos, num)
	return err
}
func printErrSafed(err *msg.Error, pos string, num interface{}) {
	if err.Code > msg.ErrCode_Err_Safed {
		logs.Debugf(err.Result)
		return
	}
	str0 := fmt.Sprintf("ErrCode:%+v,pos:%s %+v", err.Code, pos, num)
	if err.ErrString != "" {
		str0 = fmt.Sprintf(str0+",Err: %s", err.ErrString)
	}
	if err.Result != "" {
		str0 = fmt.Sprintf(str0+",Result: %s", err.Result)
	}
	logs.Errorf(str0)
}
func NewErr(code msg.ErrCode, pos string, num interface{}, v ...interface{}) *msg.Error {
	var err *msg.Error
	if v == nil || len(v) == 0 {
		err = &msg.Error{Code: code}
	} else {
		str0, str1 := combString(v...)
		err = &msg.Error{Code: code, Result: str0, ErrString: str1}

	}
	printErr(err, pos, num)
	return err
}
func ToError(err *msg.Error) error {
	return fmt.Errorf(err.ErrString)
}
func printErr(err *msg.Error, pos string, num interface{}) {
	if err.Code > msg.ErrCode_Err_Safed {
		logs.Debugf(err.Result)
		return
	}
	str0 := fmt.Sprintf("----!@!@!@!@ [err] --- Code:%+v,pos:%s %+v", err.Code, pos, num)
	if err.ErrString != "" {
		str0 = fmt.Sprintf(str0+",Err: %s", err.ErrString)
	}
	if err.Result != "" {
		str0 = fmt.Sprintf(str0+",Result: %s", err.Result)
	}
	logs.Errorf(str0)
	// if !cfg.IsEnvRelease() {
	logs.Errorf("%s", debug.Stack())
	// }
}

//	func linkString(split string, vals ...interface{}) string {
//		k := ""
//		for _, v := range vals {
//			if k == "" {
//				k = fmt.Sprintf("%+v", v)
//			} else {
//				k = fmt.Sprintf("%+v%s%+v", k, split, v)
//			}
//		}
//		return k
//	}
func combString(vals ...interface{}) (string, string) {
	strResult := ""
	strError := ""
	for _, v := range vals {
		if err, ok := v.(error); ok {
			strError = err.Error()
		} else {
			if strResult == "" {
				strResult = fmt.Sprintf("%+v", v)
			} else {
				strResult = fmt.Sprintf("%+v%+v", strResult, v)
			}
		}
	}
	// logs.Debugf("-------strResult --:%s", strResult)
	// logs.Debugf("-------strError --:%s", strError)
	return strResult, strError
}
